#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# server-python.py
# Name:Yiming Zhang
# NetId:10235101501
###############################################################################

import sys
import socket
import os

RECV_BUFFER_SIZE = 2048
QUEUE_LENGTH = 10


def server(server_port):
    """TODO: Listen on socket and print received message to sys.stdout"""
    HOST=None #HOST=''
    PORT=server_port
    s=None
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except OSError as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(QUEUE_LENGTH)
        except OSError as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print ('could not open socket')
        sys.exit(1)
    while 1:
        conn, addr = s.accept()
        data = conn.recv(RECV_BUFFER_SIZE)
        # accept need to be put in the cycle
        while data: 
            os.write(1,data)   
            data = conn.recv(RECV_BUFFER_SIZE) 




def main():
    """Parse command-line argument and call server function """
    if len(sys.argv) != 2:
        sys.exit("Usage: python server-python.py [Server Port]")
    server_port = int(sys.argv[1])
    server(server_port)

if __name__ == "__main__":
    main()

